package me.sluijsens.AntiEnderman;

import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityTeleportEvent;

public class EntityListener implements Listener {
	private AntiEnderman plugin = null;
	private ConfigHandler conf = null;

	public EntityListener(AntiEnderman instance) {
		this.plugin = instance;
	}

	@EventHandler(priority = EventPriority.NORMAL)
	public void onCreatureSpawn(CreatureSpawnEvent event) {
		conf = plugin.getConf();
		Entity entity = event.getEntity();
		String world = entity.getWorld().getName();

		if (entity instanceof Enderman
				&& conf.isSet("block." + world + ".enderman.spawn")) {
			event.setCancelled(conf.getBoolean("block." + world
					+ ".enderman.spawn"));
		} else if (entity instanceof Enderman) {
			event.setCancelled(conf.getBoolean("block.enderman.spawn"));
		}
	}

	@EventHandler(priority = EventPriority.NORMAL)
	public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) {
		conf = plugin.getConf();
		Entity entity = event.getEntity();

		int from = event.getBlock().getTypeId();
		int to = event.getTo().getId();

		String world = entity.getWorld().getName();

		boolean further = false;

		if (entity instanceof Enderman
				&& conf.isSet("block." + world + ".enderman.place")
				&& from == 0)
			further = conf.getBoolean("block." + world + ".enderman.place");
		else if (entity instanceof Enderman && from == 0)
			further = conf.getBoolean("block.enderman.place");
		else if (entity instanceof Enderman
				&& conf.isSet("block." + world + ".enderman.break") && to == 0)
			further = true;
		else if (entity instanceof Enderman && to == 0)
			further = conf.getBoolean("block.enderman.break");

		if (further) {
			boolean setBlockIDs = conf.isSet("block.enderman.blockIDs");
			String BlockIDs[] = null;
			String BlockID = null;

			if (setBlockIDs) {
				BlockIDs = conf.getString("block.enderman.blockIDs").split(",");

				BlockID = event.getBlock().toString();
				plugin.getServer().broadcastMessage(BlockID);
			}

			if (!setBlockIDs || setBlockIDs
					&& plugin.in_Array(BlockIDs, BlockID)) {
				event.setCancelled(true);
			}
		}
	}

	@EventHandler(priority = EventPriority.NORMAL)
	public void onEndermanTeleport(EntityTeleportEvent event) {
		conf = plugin.getConf();
		Entity entity = event.getEntity();
		String world = entity.getWorld().getName();

		if (entity instanceof Enderman
				&& conf.isSet("block." + world + ".enderman.teleport")) {
			event.setCancelled(conf.getBoolean("block." + world
					+ ".enderman.teleport"));
		} else {
			event.setCancelled(conf.getBoolean("block.enderman.teleport"));
		}
	}
}
